﻿using System;
using System.Xml.Serialization;
using CuteAnt.Log;

namespace CuteAnt.Configuration
{
	/// <summary>Log设置描述类, 加[Serializable]标记为可序列化</summary>
	[Serializable]
	[XmlRoot("configuration", IsNullable = false)]
	public class LogConfigInfo : ConfigInfoBase
	{
		#region -- 属性 --

		//private String _LogPath = "Log" + Path.DirectorySeparatorChar;

		///// <summary>
		///// 日志目录：默认为当前目录下的Log文件夹。生产环境建议输出到站点外单独的Log目录
		///// </summary>
		//public String LogPath
		//{
		//  get { return _LogPath; }
		//  set { _LogPath = value; }
		//}

		//private String _BackupLogPath = "Log_Backup" + Path.DirectorySeparatorChar;

		///// <summary>
		///// 日志备份目录：默认为当前目录下的log_backup文件夹。生产环境建议输出到站点外单独的HmTemp目录
		///// </summary>
		//public String BackupLogPath
		//{
		//  get { return _BackupLogPath; }
		//  set { _BackupLogPath = value; }
		//}

		private String _BackupFileSize = ""; // 默认备份，因为使用日期（或小时）分文件存储日志足够了

		/// <summary>
		/// 日志文件大小，三种方式：1 mb；1024 kb；1048576，为空则不作备份
		/// 只要制定了备份日志文件大小之后，不管任何命名方式都备份
		/// </summary>
		public String BackupFileSize
		{
			get { return _BackupFileSize; }
			set { _BackupFileSize = value; }
		}

		private String _ClearHour = "30 d"; // 自动清理备份文件夹中30天之前的日志

		/// <summary>清除备份log文件的时间，三种方式：30 m（月）; 30 d（天）; 30 h（小时），为空则不作清理</summary>
		public String ClearHour
		{
			get { return _ClearHour; }
			set { _ClearHour = value; }
		}

		private Int32 _TimedLog = 1; // 以日期命名日志文件

		/// <summary>日志文件命名方式：1 - 按日期命名；2 - 按日期小时命名；3 - 按日期小时分钟命名；其他数值：使用LogFileName设定的名字</summary>
		public Int32 TimedLog
		{
			get { return _TimedLog; }
			set { _TimedLog = value; }
		}

		private String _LogFileName = ""; // 手动指定日志文件名称

		/// <summary>日志文件名称：默认为空，系统自动根据时间命名</summary>
		public String LogFileName
		{
			get { return _LogFileName; }
			set { _LogFileName = value; }
		}

		//private String _AllowLogAction = "Write|Info|Error|Warn|SQL";

		///// <summary>
		///// 允许存储的日志类别
		///// </summary>
		//public String AllowLogAction
		//{
		//  get { return _AllowLogAction; }
		//  set { _AllowLogAction = value; }
		//}

		private Int32 _ThinkTime = 5000;

		/// <summary>日志线程思考时间，单位毫秒</summary>
		public Int32 ThinkTime
		{
			get { return _ThinkTime; }
			set { _ThinkTime = value; }
		}

		private Boolean _IsMutex = false;

		/// <summary>是否需要互拆对象，进程级别</summary>
		public Boolean IsMutex
		{
			get { return _IsMutex; }
			set { _IsMutex = value; }
		}

		private String _MutexName = "LogMutex4Hm";

		/// <summary>互拆对象命名</summary>
		public String MutexName
		{
			get { return _MutexName; }
			set { _MutexName = value; }
		}

		private Int32 _SecurityMemNumber = 0;

		/// <summary>队列最大缓存数目：值为0则不限制</summary>
		public Int32 SecurityMemNumber
		{
			get { return _SecurityMemNumber; }
			set { _SecurityMemNumber = value; }
		}

		#endregion

		#region -- override method Init --

		protected internal override void Init()
		{
			var debug = new ConfigCustomItem();
			debug.Name = "Debug";
			debug.Value = @"Path=Log\;Level=All";
			//var management = new ConfigCustomItem();
			//management.Name = "Management";
			//management.Value = @"Path=Log\Management\;BakPath=Log\Management_Bak\;AllowLogAction=Write";
			//var mis = new ConfigCustomItem();
			//mis.Name = "Mis";
			//mis.Value = @"Path=Log\Mis\;BakPath=Log\Mis_Bak\;AllowLogAction=Write";
			//var im = new ConfigCustomItem();
			//im.Name = "IM";
			//im.Value = @"Path=Log\Im\;BakPath=Log\Im_Bak\;AllowLogAction=Write";
			//var file = new ConfigCustomItem();
			//file.Name = "File";
			//file.Value = @"Path=Log\File\;BakPath=Log\File_Bak\;AllowLogAction=Write";
			//var smtp = new ConfigCustomItem();
			//smtp.Name = "Smtp";
			//smtp.Value = @"Path=Log\Smtp\;BakPath=Log\Smtp_Bak\;AllowLogAction=Write";
			//var pop = new ConfigCustomItem();
			//pop.Name = "Pop3";
			//pop.Value = @"Path=Log\Pop\;BakPath=Log\Pop_Bak\;AllowLogAction=Write";
			//var imap = new ConfigCustomItem();
			//imap.Name = "Imap";
			//imap.Value = @"Path=Log\Imap\;BakPath=Log\Imap_Bak\;AllowLogAction=Write";
			//var relay = new ConfigCustomItem();
			//relay.Name = "Relay";
			//relay.Value = @"Path=Log\Relay\;BakPath=Log\Relay_Bak\;AllowLogAction=Write";
			//var fetch = new ConfigCustomItem();
			//fetch.Name = "Fetch";
			//fetch.Value = @"Path=Log\Fetch\;BakPath=Log\Fetch_Bak\;AllowLogAction=Write";
			//var sip = new ConfigCustomItem();
			//sip.Name = "Sip";
			//sip.Value = @"Path=Log\Sip\;BakPath=Log\Sip_Bak\;AllowLogAction=Write";
			CustomItems = new ConfigCustomItem[] { debug }; //, management, mis, im, file, smtp, pop, imap, relay, fetch, sip };
		}

		#endregion

		#region -- 辅助方法 --

		///// <summary>取得允许的Log输出模式</summary>
		///// <param name="action" type="string">
		///// <para></para>
		///// </param>
		///// <returns>A int value...</returns>
		//public static Int32 GetAllowLogAction(String action)
		//{
		//	//String action = AllowLogAction;
		//	if (action.IsNullOrWhiteSpace())
		//	{
		//		return (Int32)(LogAction.Write);
		//	}
		//	else
		//	{
		//		String[] acs = action.Split(new Char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
		//		Int32 v = 0;
		//		for (Int32 i = 0; i < acs.Length; i++)
		//		{
		//			try
		//			{
		//				LogAction ac = (LogAction)Enum.Parse(typeof(LogAction), acs[i], true);
		//				v |= (Int32)ac;
		//			}
		//			catch
		//			{
		//				return (Int32)(LogAction.Write);
		//			}
		//		}
		//		return v;
		//	}
		//}

		/// <summary>解析Log输出级别</summary>
		public static LogLevel ParseLogLevel(String level)
		{
			if (level.IsNullOrWhiteSpace())
			{
				return LogLevel.All;
			}
			else
			{
				try
				{
					return (LogLevel)Enum.Parse(typeof(LogLevel), level, true);
				}
				catch
				{
					return LogLevel.All;
				}
			}
		}

		/// <summary>日志文件大小，备份时需要。</summary>
		/// <returns>A long value...</returns>
		public Int64 GetBackupFileSize()
		{
			if (BackupFileSize.IsNullOrWhiteSpace()) { return 0; }
			String size = BackupFileSize;
			if (size.EndsWith("mb", StringComparison.InvariantCultureIgnoreCase))
			{
				size = size.Substring(0, size.Length - 2);
				return size.ToInt64() * 1024 * 1024;
			}
			else if (size.EndsWith("kb", StringComparison.InvariantCultureIgnoreCase))
			{
				size = size.Substring(0, size.Length - 2);
				return size.ToInt64() * 1024;
			}
			else
			{
				return size.ToInt64();
			}
		}

		/// <summary>自动清除日志文件期限</summary>
		/// <returns>A int value...</returns>
		public Int32 GetClearHour()
		{
			if (ClearHour.IsNullOrWhiteSpace()) { return 0; }
			String hour = ClearHour;
			if (hour.EndsWith("m", StringComparison.InvariantCultureIgnoreCase))
			{
				hour = hour.Substring(0, hour.Length - 1);
				return hour.ToInt() * 24 * 30;
			}
			else if (hour.EndsWith("d", StringComparison.InvariantCultureIgnoreCase))
			{
				hour = hour.Substring(0, hour.Length - 1);
				return hour.ToInt() * 24;
			}
			else if (hour.EndsWith("h", StringComparison.InvariantCultureIgnoreCase))
			{
				hour = hour.Substring(0, hour.Length - 1);
				return hour.ToInt();
			}
			else
			{
				return hour.ToInt();
			}
		}

		#endregion
	}

	/// <summary>Log配置管理</summary>
	/// <remarks></remarks>
	public class LogConfigs : BaseConfigs<LogConfigs, LogConfigInfo>
	{
		static LogConfigs()
		{
			m_configManager = ConfigFileManager<LogConfigInfo>.Create("Log", "Config");
		}
	}
}